package com.feinno.module.security.web;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.feinno.framework.common.web.AbstractController;
import com.feinno.module.security.domain.Resource;
import com.feinno.module.security.domain.Role;
import com.feinno.module.security.service.ResourceService;
import com.feinno.module.security.service.RoleService;
import com.feinno.module.security.shiro.realm.ShiroDbRealm;

@Controller
@RequestMapping(value = "/admin/system/role")
public class RoleController extends AbstractController<Role, RoleService> {

	@Autowired
	@SuppressWarnings("unused")
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private ShiroDbRealm shiroDbRealm;
	
	@Override
	protected void onSave(Role entity, Model model, HttpServletRequest request, HttpServletResponse response, boolean isCreate) {
		String resStr = request.getParameter("res");
		resStr = resStr.substring(0, resStr.length() - 1);
		String[] resArray = resStr.split("\\|");
		List<String> resourcelist = new ArrayList<String>();
		for (int i = 0; i < resArray.length; i++) {
			resourcelist.add(resArray[i]);
		}
		HashSet<Resource> resources = new HashSet<Resource>();
		for (String roleid : resourcelist) {
			Resource resource = resourceService.get(Long.valueOf(roleid));
			resources.add(resource);
		}
		entity.setRescs(resources);
		super.onSave(entity, model, request, response, isCreate);
		// 清空权限缓存
		shiroDbRealm.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
	}

	@Override
	protected void referenceData(HttpServletRequest request, Map<String, Object> model) {
		List<Resource> allResources = resourceService.getAll();
		model.put("resources", allResources);
	}

}
